
add_comma <- function(x, ...) {
  format(x, ..., big.mark = ",", scientific = FALSE, trim = TRUE)
}

load('summary_data/table1.rda')
out_rs = clean_names(out_rs)

left_join(
  out_rs,
  out_rs %>% 
    group_by(top_10) %>%
    summarize(tot_by_class = sum(n)) %>%
    ungroup(),
  by = "top_10"
) %>%
  mutate(pct = (n / tot_by_class) %>% scales::percent(., accuracy = 1, suffix = "\\%")) %>%
  select(top_10, year2012, year2016, year2020, pct, n) %>% 
  arrange(desc(top_10), year2012, year2016, year2020) %>%
  mutate(n = add_comma(n)) %>%
  mutate(
    top_10 = stringr::str_replace(top_10, "\\%", "\\\\%"),
    top_10 = stringr::str_replace(top_10, "Matched Donors in the", "")
  ) %>%
  rename(
    `Wealth Bin` = top_10,
    `2012` = year2012,
    `2016` = year2016,
    `2020` = year2020,
    `\\% of Donors` = pct
  ) %>% 
  kableExtra::kbl(
    format   = "latex", 
    caption  = "Percent of Donors Giving in One, Two, or Three Cycles, by Wealth Bin",
    align    = c(rep("l", 4), rep("r", 2)),
    booktabs = TRUE,
    escape   = FALSE
  ) %>% 
  collapse_rows(1, latex_hline = "major") %>%
  kable_styling(full_width = FALSE, font_size = 8) %>%
  save_kable(file = 'tables/table1.tex')
